<template>
  <div class="content">
    <el-card class="content-card">
      <div slot="header" class="content-card-header">
        <span>设置我的资料</span>
      </div>
      <div class="content-card-body">
        <el-form label-width="80px" :model="form">
          <el-form-item label="头像">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              :data-id="form.id || 0"
              action="https://jsonplaceholder.typicode.com/posts/"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="form.username" placeholder="请输入用户名" :disabled="true" clearable />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="form.nickname" placeholder="请输入昵称" clearable />
          </el-form-item>
          <el-form-item label="博客用户">
            <el-button v-if="!form.userId" type="danger" size="small" @click="bindUserDialogVisible = true">绑定用户</el-button>
            <el-button v-if="form.userId" size="small" @click="handleUserInfoForm">查看用户信息</el-button>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.description" :rows="4" type="textarea" placeholder="请输入描述信息..." />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="medium" @click="handleUpdate">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-dialog
      title="绑定博客用户"
      :visible.sync="bindUserDialogVisible"
      width="30%"
    >
      <el-form ref="bindForm" label-width="80px" :rules="bindFormRules" :model="bindForm" style="width: 85%;">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="bindForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bindUserDialogVisible = false">取 消</el-button>
        <el-button :loading="bindUserBttonLoading" type="primary" @click="bindUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="博客信息"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-press-escape="false"
    >
      <el-form label-width="80px" label-position="top" :model="userInfoForm">
        <el-form-item label="微信号">
          <el-input v-model="userInfoForm.weChat" />
        </el-form-item>
        <el-form-item label="QQ">
          <el-input v-model="userInfoForm.qq" />
        </el-form-item>
        <el-form-item label="二维码">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleQrCodeUploadSuccess"
            :before-upload="beforeUpload"
            :data-id="form.id || 0"
            action="https://jsonplaceholder.typicode.com/posts/"
          >
            <img v-if="qrCode" :src="qrCode" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="个人简介">
          <mavon-editor
            v-model="userInfoForm.personalProfile"
            placeholder="请输入你的内容..."
            :code-style="mavonEditor.code_style"
            @change="mavonChange"
            @save="mavonSave"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor'
import { upload } from '@/api/support'
import { getInfo, update, bind } from '@/api/admin'
import { getUserInfo, updateUserInfo } from '@/api/user'

export default {
  components: {
    mavonEditor
  },
  data() {
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请正确填写邮箱'))
      } else {
        if (value !== '') {
          var reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
          if (!reg.test(value)) {
            callback(new Error('请输入有效的邮箱'))
          }
        }
        callback()
      }
    }
    return {
      bindUserDialogVisible: false,
      bindUserBttonLoading: false,
      dialogVisible: false,
      form: {},
      imageUrl: '',
      bindForm: {
        email: ''
      },
      bindFormRules: {
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'change' },
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      mavonEditor: {
        code_style: 'atom-one-dark',
        navigation: true
      },
      userInfoForm: {},
      qrCode: ''
    }
  },
  watch: {
    'form.avatar': function(newImage) {
      if (newImage.indexOf('http') > -1) {
        this.imageUrl = newImage
      }
    },
    'form.userId': function(newUserId) {
      this.userInfoForm.userId = newUserId
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    getInfo() {
      getInfo().then(response => {
        if (response.code === 200) {
          this.form = response.data
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },
    // 上传管理员头像成功
    handleUploadSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.article.image = this.imageUrl
      this.handleUpload(file, 2)
    },
    // 上传联系二维码成功
    handleQrCodeUploadSuccess(res, file) {
      this.qrCode = URL.createObjectURL(file.raw)
      this.userInfoForm.qrCode = this.qrCode
      this.handleUpload(file, 3)
    },
    // 上传之前判断是否是图片
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传文件，获取文件流
    handleUpload(file, code) {
      const raw = file.raw
      const formData = new FormData()
      formData.append('objectId', this.$refs.upload.$el.getAttribute('data-id'))
      formData.append('code', code)
      formData.append('files', raw)
      upload(formData).then(response => {
        if (response.code === 200) {
          this.form.avatar = response.data.url
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 更新操作
    handleUpdate() {
      update(this.form).then(response => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },
    // 绑定用户
    bindUser() {
      this.$refs.bindForm.validate((valid) => {
        if (valid) {
          this.bindUserBttonLoading = true
          bind(this.bindForm).then(response => {
            if (response.code === 200) {
              this.getInfo()
              this.$message({
                type: 'success',
                message: '绑定成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: response.message
              })
            }
            this.bindUserBttonLoading = false
            this.bindUserDialogVisible = false
          })
        } else {
          this.$message({
            type: 'error',
            message: '输入有误，请重新检查'
          })
          return false
        }
      })
    },
    // 打开获取个人信息窗口
    handleUserInfoForm() {
      this.dialogVisible = true
      // 获取博客用户信息
      getUserInfo(this.userInfoForm.userId).then(response => {
        if (response.code === 200) {
          this.userInfoForm = response.data
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      })
    },
    // 更新用户个人信息
    handleUpdateUserInfo() {
      updateUserInfo(this.userInfoForm).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '请求失败',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
        this.dialogVisible = false
      })
    },
    /** mavonEditor */
    // 改变
    mavonChange(value, render) {
      // console.log(value)
      // console.log(marked(render))
    },
    // 保存
    mavonSave(value, render) {
      console.log(value)
      console.log(render)
    }
  }
}
</script>

<style lang="scss">
  /** 上传图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-top: 14px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    background-color: #fff
  }
</style>

<style lang="scss" scoped>
  .content {
    padding: 20px;
  }

  .content-card-header:before,
  .content-card-header:after {
    display: table;
    content: "";
  }
  .content-card-header:after {
    clear: both
  }

  .content-card-body {
    width: 460px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
